package com.imooc.mmall.readwrite;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;


@Slf4j
public class DynamicDataSourceAspect {

    public void pointCut(){};

    public void before(JoinPoint point)
    {
        Object target = point.getTarget();
        String methodName = point.getSignature().getName();
        Class<?>[] clazz = target.getClass().getInterfaces();
        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
        try {
            Method method = clazz[0].getMethod(methodName, parameterTypes);
            //判断方法是否加了注解，加了则默认走注解定义的val值，最终去拿DataSource
            if (method != null && method.isAnnotationPresent(TargetDataSource.class)) {
                TargetDataSource data = method.getAnnotation(TargetDataSource.class);
                DynamicDataSourceHolder.putDataSource(data.value());
            }else{
                //如果没加注释，默认根据自定义条件判定
                if(methodName.startsWith("select")||methodName.startsWith("get")||methodName.startsWith("query")){
                    //select、get、query、默认走读属于
                    DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.READ);
                }else if(methodName.startsWith("update")||methodName.startsWith("insert")
                        ||methodName.startsWith("save")||methodName.startsWith("delete")){
                    //update、insert、save、delete、默认走写
                    DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.WRITE);
                }else{
                    DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.WRITE);
                }
            }
        } catch (Exception e) {
            log.error(String.format("Choose DataSource error, method:%s, msg:%s", methodName, e.getMessage()));
        }
    }

    public void after(JoinPoint point) {
        DynamicDataSourceHolder.clearDataSource();
    }
}